<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
    <title>GE StreamLayer - Seattle Buses - store size</title>
    <link rel="stylesheet" href="https://js.arcgis.com/3.16/dijit/themes/tundra/tundra.css">
    <link rel="stylesheet" href="https://js.arcgis.com/3.16/esri/css/esri.css">
    <style type="text/css">
      html, body, #map {
        height: 100%; width: 100%;
        margin: 0; padding: 0;
      }
      #info {
        background-color: #000;
        z-index: 92;
        left: 0px;
        bottom: 0px;
        position: absolute;  
        padding: 10px;
        font-family: Segoe UI;
        color: #fff;
        width: 350px;
        border-top-right-radius: 8px;
        opacity: 0.7;
        max-height: 80%;
        font-size: 14pt;
      }
    </style>
    <script src="https://js.arcgis.com/3.16/"></script>
  </head>
  <body class="tundra">
    <div id="map"></div>
    <div id="info">
      <div id="counter"><h1>Coffee shops near public transit</h1>
      This app captures the number of times city buses pass in front of 
        each Starbucks location in Seattle.<br><br>
    </div>
      <div id="legendDiv"></div>
    </div>
  </body>
  <script>
    require(["esri/map",
      "esri/layers/StreamLayer",
      "esri/layers/FeatureLayer",
      "esri/dijit/PopupTemplate",
      "esri/graphic",
      "esri/symbols/SimpleLineSymbol",
      "esri/symbols/SimpleMarkerSymbol",
      "esri/geometry/geometryEngine",
      "esri/renderers/SimpleRenderer",
      "esri/renderers/smartMapping",
      "esri/graphicsUtils",
      "esri/tasks/query",
      "esri/dijit/Legend",
      "dojo/_base/Color",
      "dojo/_base/array",
      "dojo/on",
      "dojo/dom",
      "dojo/domReady!"
    ], function(Map, StreamLayer, FeatureLayer, PopupTemplate, Graphic,
                SimpleLineSymbol, SimpleMarkerSymbol, geometryEngine, 
                 SimpleRenderer, smartMapping, graphicsUtils, Query, Legend, 
                 Color, arrayUtils, on, dom) {
      
          var map, starbucksLayer, timeNode, starbucksGeoFences, legend, 
              streamLayer, avgNode, startTime, busLocations = [];
      
      function init(){
        map = new Map("map", {
          basemap: "gray",
          center: [-122.3477549305, 47.61093593305],
          zoom: 14
        });
        
        var storeRenderer = new SimpleRenderer(new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE, 10, 
          new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color("white"), 0.5),
           new Color("#3F8D6E")));

        starbucksLayer = new FeatureLayer("http://services.arcgis.com/V6ZHFr6zdgNZuVG0/arcgis/rest/services/Starbucks_Locations/FeatureServer/0", {
          definitionExpression: "City = 'Seattle'",
          outFields: ["*"],
          infoTemplate: new PopupTemplate({
            title: "{Name}",
            description: "{Brand} store number: {Store_Number}"
          })
        });
        
        starbucksLayer.setRenderer(storeRenderer);
        
        avgNode = dom.byId("displayAvg");
        timeNode = dom.byId("since");
        
        var params = new Query();
        params.returnGeometry = true;
        params.where = "1=1";
        
        starbucksLayer.queryFeatures(params, function(result){
          var starbucksLocations = result.features;
          starbucksGeoFences = arrayUtils.map(starbucksLocations, function(store, i){
            var tempGeom = geometryEngine.geodesicBuffer(store.geometry, 150, "yards");
            var tempGraphic = new Graphic(tempGeom, null, store.attributes);
            return tempGraphic;
          });
        });
        
        toggleStreamLayer();
        
        map.on("load", function(){
          legend = new Legend({
            map: map,
            layerInfos: [
              {
                layer: starbucksLayer,
                title: "Number of buses that passed each store"
              }, {
                layer: streamLayer,
                title: "Public Transportation"
              }
            ]
          }, "legendDiv");
          legend.startup();
        }); 
      }
      
      /*************************************************
       *
       * Functions to add and remove Stream Layer
       *
       *************************************************/
      function toggleStreamLayer(){
        if(streamLayer){
          removeStreamLayer();
        }
        else{
          addStreamLayer();
          startTime = new Date();
        }
      }

      function addStreamLayer(){
        //url to stream service
        var svcUrl = "https://geoeventsample3.esri.com:6443/arcgis/rest/services/SeattleBus/StreamServer";

        //construct Stream Layer
        streamLayer = new StreamLayer(svcUrl, {
          purgeOptions: { displayCount: 10000 },
          infoTemplate: new PopupTemplate({
            title: "Bus number {BusNo}",
            description: "{DateTimeStamp}"
          }),
          opacity: 0.75
        });
        
        var renderer = new SimpleRenderer(new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE, 10, 
          new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color("white"), 1),
           new Color([255, 128, 0, 0.8])));
        
        renderer.label = "City bus location";
        streamLayer.setRenderer(renderer);

        //When layer loads, register listeners for layer events and add layer to map
        streamLayer.on("load", function(){
          
          streamLayer.on("graphic-add", function(evt){
            busLocations.push(evt.graphic.geometry);
          });

          //Add layer to map
          map.addLayers([streamLayer, starbucksLayer]);
          
          window.setInterval(function(){
            var params = {
              basemap: "gray",
              layer: starbucksLayer,
              optimizeForScale: true,
              field: function(graphic){
                var num = 0;
                arrayUtils.forEach(busLocations, function(bus, i){
                  var fence = arrayUtils.filter(starbucksGeoFences, function(geoFence, i){
                    return geoFence.attributes.Store_ID === graphic.attributes.Store_ID;
                  });
                  if(geometryEngine.intersects(bus, fence[0].geometry)){
                    num++;
                  }
                });
                return num;
              }
            };
            
            smartMapping.createSizeInfo(params).then(function(response){
              starbucksLayer.renderer.label = "Starbucks store location";
              starbucksLayer.renderer.setVisualVariables([response.sizeInfo]);
              starbucksLayer.redraw();
              legend.refresh();
            });
          }, 10000);
        });
      }

      function removeStreamLayer(){
        if (streamLayer){
          map.removeLayer(streamLayer);
          streamLayer = null;
          map.graphics.clear();
        }
      }

      init();
    });
  </script>
</html>
